package top.mindse.word2pdf.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.jodconverter.DocumentConverter;
import org.jodconverter.boot.autoconfigure.JodConverterProperties;
import org.jodconverter.document.DocumentFormat;
import org.jodconverter.office.OfficeException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import top.mindse.word2pdf.service.IFileService;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author zhuzhiping
 * @description 逻辑处理
 * @date 2021/1/18 18:20
 */

@Service
@Slf4j
public class FileServiceImpl implements IFileService {

    @Resource
    private DocumentConverter documentConverter;


    @Resource
    private JodConverterProperties properties;

    @Override
    public String convertWord2PDF(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return "上传失败，请选择文件";
        }
        String officeHome = properties.getOfficeHome();
        String fileName = String.valueOf(System.currentTimeMillis());
        File target = new File(officeHome + "pdf/" + fileName + ".pdf");
        try (InputStream source = file.getInputStream()) {
            DocumentFormat documentFormat = documentConverter.getFormatRegistry().getFormatByExtension("pdf");
            documentConverter.convert(source).as(documentFormat).to(target).execute();



        } catch (IOException | OfficeException e) {
            log.error("文件转换错误", e);
        }
        return target.getAbsolutePath();
    }
}
